using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;

namespace Avanzis.QueryObjects
{
    internal class QueryObjectsHelper
    {
        /// <summary>
        /// Gets the dictionary from the current row of the DbDataReader
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns></returns>
        public static IDictionary<string, object> GetDictionaryFromReader(DbDataReader reader)
        {
            if (reader == null) throw new ArgumentNullException("reader");
            if (reader.IsClosed) throw new QueryObjectsException("Reader is closed"); 
                       
            IDictionary<string, object> dictionary = new Dictionary<string, object>();

            for (int i = 0; i < reader.FieldCount; i++)
            {                
                dictionary.Add(reader.GetName(i), reader.GetValue(i));              
            }

            return dictionary;
        }

        /// <summary>
        /// Builds the array.
        /// </summary>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static Array BuildArray(Type targetType, IList list)
        {
            Array array = Array.CreateInstance(targetType, list.Count);

            list.CopyTo(array, 0);

            return array;
        }
    }
}
